package com.example.hometown_walker.exception;

import com.example.hometown_walker.util.json.JsonUtil;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

/**
 * @description: SpringCloud-feign客户端统一处理下游服务自定义异常
 * <p>
 * @author: chenchaoran
 * @date: 2020-04-02
 */
@Slf4j
public class ServiceFeignErrorDecoder implements ErrorDecoder {
    private ErrorDecoder defaultErrorDecoder = new Default();

    @Override
    public Exception decode(String s, Response response) {
        if (response.status() >= HttpStatus.BAD_REQUEST.value()
                && response.status() < HttpStatus.INTERNAL_SERVER_ERROR.value()) {
            try {
                String body = Util.toString(response.body().asReader());
                ServiceException se = JsonUtil.of(body, ServiceException.class);
                if (se != null) {
                    return se;
                }
            } catch (Exception e) {
                log.error("CgFeignErrorDecoder", e);
            }
            return new ServiceException(CoreErrorCode.SYSTEM_FEIGN_ERROR);
        }
        return defaultErrorDecoder.decode(s, response);

    }
}
